package main

import (
	"context"
	"crypto/tls"
	"fmt"
	"net"
	"time"
)

func tlsConnect(conn *net.TCPConn, server string) (*tls.Conn, error) {
	cf := &tls.Config{
		InsecureSkipVerify: true,
		ServerName:         server,
	}
	cn := tls.Client(conn, cf)
	errc := make(chan error, 2)
	timeout := time.Minute
	timer := time.AfterFunc(timeout, func() { errc <- fmt.Errorf("TLS handshake timeout (%fs)", timeout.Seconds()) })
	go func() {
		err := cn.HandshakeContext(context.Background())
		timer.Stop()
		errc <- err
	}()
	if err := <-errc; err != nil {
		return nil, err
	}
	cs := cn.ConnectionState()
	wout("TLS handshake ok: version=[%s]", tls.VersionName(cs.Version))
	return cn, nil
}
